package com.gopay.scheduler.service.cacert.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cert.CertCustPolicyEntity;
import com.gopay.scheduler.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.gopay.common.constants.cust.CustCaCertConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.cps.dao.acct.CommonQueryDAO;
import com.gopay.common.domain.cps.transfer.Trans00605VO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.domain.cust.CustCaBuyDtl;
import com.gopay.common.domain.cust.CustCaCert;
import com.gopay.common.domain.mail.Send;
import com.gopay.common.exception.GopayException;
import com.gopay.common.security.cacert.dao.CustCaCertQueryDao;
import com.gopay.common.util.DateUtils;
import com.gopay.cron.web.util.CallCPSUtil;
import com.gopay.cron.web.util.RemoteServiceUtil;
import com.gopay.remote.cps.mail.MailRemoteService;
import com.gopay.scheduler.job.vo.CustInfo;
import com.gopay.scheduler.service.cacert.CustCaCertService;

/**
 * 
 * @CustCaCertServiceImpl.java
 * @author dongdh
 * @2016年2月15日 下午5:02:43 www.gopay.com.cn Inc.All rights reserved.
 */
@Service("custCaCertServiceCron")
public class CustCaCertServiceImpl implements CustCaCertService {

	/**
	 * 定义日志对象
	 */
	private static final Logger logger = LoggerFactory.getLogger(CustCaCertServiceImpl.class);
	private @Value("#{webProperties['remotenotify.cps.mail.url']}") String notifyEmailUrl;

	@Resource(name = "comQueryDao")
	private CommonQueryDAO commonDao;

	@Resource(name = "custCaCertQueryDao")
	private CustCaCertQueryDao custCaCertQueryDao;
	@Resource(name = "custCaCertDAO")
	private CustCaCertDAO custCaCertDAO;
	@Autowired
	private CustCaBuyDtlWriteDao custCaBuyDtlWriteDao;
	@Autowired
	private CustCaBuyDtlReadDao custCaBuyDtlReadDao;

	@Resource(name ="cpsGeneralMainOrderQueryDAO")
	private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderQueryDAO;

	@Resource(name = "certCustPolicyEntityDao")
	private CertCustPolicyEntityDao certCustPolicyEntityDao;

	@Override
	public List<CustInfo> getCustList() {

		String sql = buildSql();

		Map<String, Object> param = new HashMap<>();
		List<Object[]> list = commonDao.findBySql(sql, param);

		return buildCustInfoList(list);
	}

	/**
	 * 构建返回的客户列表
	 * 
	 * @param list
	 * @return
	 */
	private List<CustInfo> buildCustInfoList(List<Object[]> list) {

		List<CustInfo> custList = new ArrayList<>();

		if (list != null && list.size() > 0) {
			CustInfo cust = null;
			for (Object[] arr : list) {
				cust = new CustInfo();
				if (arr[0] != null) {
					cust.setCustId(arr[0].toString());
				}

				if (arr[1] != null) {
					cust.setCustName(arr[1].toString());
				}

				if (arr[2] != null) {
					cust.setCustEmail(arr[2].toString());
				}

				if (arr[3] != null) {
					cust.setCustType(arr[3].toString());
				}

				if (arr[4] != null) {
					cust.setCustPhone(arr[4].toString());
				}

				if (arr[5] != null) {
					cust.setValidTo((Date) arr[5]);
				}
				
                if (arr[6] != null) {
                    cust.setUserId(arr[6].toString());
                }

                if (arr[7] != null) {
                    cust.setOperId(arr[7].toString());
                }
                
                if (arr[8] != null) {
                    cust.setOperName(arr[8].toString());
                }

                if (arr[9] != null) {
                    cust.setOperMobile(arr[9].toString());
                }
                
                if (arr[10] != null) {
                    cust.setCertId(arr[10].toString());
                }

				custList.add(cust);
			}
		}

		return custList;
	}

	/**
	 * 构建查询sql
	 * 
	 * @return
	 */
	private String buildSql() {

        StringBuilder sql = new StringBuilder();
        Date date=new Date();
        String dateFormat="yyyy-MM-dd";
        String currentDate=DateUtils.format(date,dateFormat);
        /**
         * 获取当前日期后30天日期
         */
        //String limitDate=this.getDate(date, CustCaCertConstants.DAY_NUM, dateFormat);
        
        //获取当前日期后1个月时间
        Date limitdate = DateUtils.add(DateUtils.getSystemDate(), Calendar.MONTH, CustCaCertConstants.CUST_CA_CERT_VALID_LIMIT);//用于进行对比的时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(limitdate);
        calendar.add(calendar.DATE,+1);//把日期往后增加一天
        date=calendar.getTime();
        String limitDate=DateUtils.format(date,dateFormat);
        
        sql.append("select ");
        sql.append("info.cust_id, ");
        sql.append("info.cust_name,");
        sql.append("info.email, ");
        sql.append("info.cust_type, ");
        sql.append("info.mob, ");
        sql.append("t.valid_to,");
        sql.append("u.user_id, ");
        sql.append("u.oper_id,");
        sql.append("u.oper_name,");
        sql.append("u.oper_mobile, ");
        sql.append("t.id ");
        
        sql.append("from cust_ca_cert t ");
        sql.append("left join user_info u on u.user_id = t.user_id "); //add by zhuliang at 2016-9-27
        sql.append("left join gopay_all_cust_info info on info.cust_id = u.cust_id ");
       // sql.append("left join cust_person_info p on (t.cust_id = p.cust_id and t.cust_type = '1') ");
        
        sql.append(" where 1=1 ");
        sql.append(" and stat= '" + CustCaCertConstants.CUST_CA_CERT_STAT_ACTIVE + "'");
        sql.append(" and VALID_TO >= TO_DATE('" + currentDate + "', 'YYYY-MM-DD') ");
        sql.append(" and VALID_TO < TO_DATE('" + limitDate + "', 'YYYY-MM-DD') ");
        logger.info("查询语句为：" + sql);
        return sql.toString();
	}

	@Override
	public List<CustCaCert> getLimitCustCaCert() {
		return custCaCertQueryDao.getLimitCustCaCert();
	}

	@Override
	public int updateCustCaCert(CustCaCert custCaCert, String stat) throws GopayException {
		int resunt = 0;
		String certId = custCaCert.getId().toString();
		if (StringUtils.isBlank(certId)) {
			logger.info("数据主键为空！" + certId);
			throw new GopayException("更新数据主键为空！");
		}
		try {
			custCaCert.setLastUptTs(DateUtils.getSystemDate());
			custCaCert.setStat(stat);
			custCaCertDAO.update(custCaCert);
			resunt = 1;
		} catch (Exception e) {
			logger.info("修改数字证书过期状态失败！" + certId, e);
			throw new GopayException("更新数据主键为空！" + e.getMessage());
		}
		return resunt;

	}

	@Override
	public void sendMail(Send send) {
		try {
			MailRemoteService mailRemoteService = this.getMailRemoteService();
			mailRemoteService.addMailTask(send);
		} catch (GopayException e) {
			logger.error("发送邮件异常：", e);
		}

	}

	private MailRemoteService getMailRemoteService() throws GopayException {
		MailRemoteService service = null;
		service = (MailRemoteService)RemoteServiceUtil.getRemoteService(MailRemoteService.class, notifyEmailUrl);
		return service;
	}
	private String getDate(Date currentDate,int dayNums,String dateFormat){
		Calendar cal = Calendar.getInstance();
		cal.setTime(currentDate);
		cal.add(Calendar.DATE, dayNums);
		return new SimpleDateFormat(dateFormat).format(cal.getTime());
	}
	/**
	 * @return the notifyEmailUrl
	 */
	public String getNotifyEmailUrl() {
		return notifyEmailUrl;
	}

	/**
	 * @param notifyEmailUrl
	 *            the notifyEmailUrl to set
	 */
	public void setNotifyEmailUrl(String notifyEmailUrl) {
		this.notifyEmailUrl = notifyEmailUrl;
	}

    @Override
    public void recoveryEquiredCert(String currentTs)throws Exception {

        List<CustCaBuyDtl> ccbdList =custCaBuyDtlReadDao.showCustCaBuyDtlByTimeAndDtlType(currentTs);
        int size = ccbdList.size();
        if(size > 0){
            for(CustCaBuyDtl ccbd : ccbdList){
                if(CustCaCertConstants.FREE_CA_CERT.equals(ccbd.getDtlType())){
					recoveryFreeCert(ccbd);
                }else if(CustCaCertConstants.PURCHASE_CA_CERT.equals(ccbd.getDtlType())){
                    logger.info("付费购买证书调用cps回收：dtlID = " + ccbd.getId());

                    Trans00605VO transVo = createTransVoByCustCaBuyDtlInfo(ccbd);
                    CPSResponse response = null;
                    try {
                        response = CallCPSUtil.callByVOTicket(transVo);
                        if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                            logger.info("回收付费购买证书退款走账异常");
                            throw new GopayException(response.getRespCode());
                        }else{
                            String orderId = (String)response.getRespData().get("gopayOrderId");
							logger.info("回收付费购买证书额度退款成功: orderId = " + orderId);
                        }
                    } catch (GopayException e) {
                        logger.error(e.getErrCode()+":"+e.getErrMsg());
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    private Trans00605VO createTransVoByCustCaBuyDtlInfo(CustCaBuyDtl ccbd) {
        Trans00605VO transVo = new Trans00605VO();
        transVo.setCustCaBuyDtlId(ccbd.getId());
		transVo.setCustType("C"); 			//企业客户数字证书回收
        transVo.setRmk("付费购买数字证书退款");
        return transVo;
    }

	/**
	 * 免费数字证书回收（赠送的）
	 * @param dtl
     */
    private void recoveryFreeCert(CustCaBuyDtl dtl){
		logger.info("免费赠送证书记录回收：dtlID = " + dtl.getId());
		dtl.setDrawbackCaCount(dtl.getUnusedCount());
		dtl.setUnusedCount(0);
		custCaBuyDtlWriteDao.update(dtl);
		logger.info("免费赠送证书记录回收成功");

		logger.info("检索数字证书个性化配置表： custId = " + dtl.getId());
		CertCustPolicyEntity policy = certCustPolicyEntityDao.findByCustId(dtl.getCustId());
		if(policy != null){//更新配置表
			logger.info("个性化配置子路不为null， 对其过期字段进行更新操作。");
			policy.setExpiredCount(dtl.getDrawbackCaCount());
			certCustPolicyEntityDao.update(policy);
		}
	}

}
